package itbour.onetouchshow.widget;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.just.agentwebX5.AgentWebX5;
import com.just.agentwebX5.ChromeClientCallbackManager;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.Calendar;

import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.web.CommWebJsContrl;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;


/**
 * Created by guoh on 2018/5/21.
 * 功能描述：广告弹框
 * 需要的参数：
 */
public class AdDialog extends Dialog {

    protected AgentWebX5 mAgentWeb;
    private ImageView iv_close;
    private LinearLayout container;

    private MVPBaseActivity mContext;
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            L_.e("暂无网络 onReceivedError");
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            L_.e("暂无网络 onReceivedHttpError");
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            L_.e("暂无网络 onReceivedSslError");
        }


    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.i("Info", "progress:" + newProgress);
        }


    };
    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {

        }
    };

    public AdDialog(@NonNull MVPBaseActivity context) {
        super(context, R.style.AdDialog);
        this.mContext = context;
        Log.e("tag", ((Activity) context).getClass().getName());
    }

    public AdDialog(@NonNull MVPBaseActivity context, int themeResId) {
        super(context, R.style.AdDialog);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_ad_dialog);
        iv_close = findViewById(R.id.iv_close);
        container = findViewById(R.id.container);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    public void setHeightAndWidth(double width, double height, String url) {
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        int screenHeight = dm.heightPixels;
        int screenWidth = dm.widthPixels;
        double dialogWidth = screenWidth / 6 * 4;
        double dialogHeight = dialogWidth / (width / height);
        final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) container.getLayoutParams();
        params.width = (int) dialogWidth;
        params.height = (int) dialogHeight;
        container.setLayoutParams(params);
//        RelativeLayout.LayoutParams imageParams= (RelativeLayout.LayoutParams) iv_close.getLayoutParams();
//        iv_close.setLayoutParams(imageParams);

        initAgentWeb(url);
        CommWebJsContrl commWebJsContrl = new CommWebJsContrl(mContext, null);
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AppConst.CONTRL, commWebJsContrl);

        //设置dialog属性
        Window window = this.getWindow();
        WindowManager.LayoutParams p = window.getAttributes();
        int bitmapWidth = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.icon_dialog_close).getWidth();
        int bitmapHeight = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.icon_dialog_close).getHeight();
        p.height = (int) (dialogHeight + bitmapHeight + UIUtils.dp2px(40 + 10));
        p.width = (int) (dialogWidth + bitmapWidth + UIUtils.dp2px(0));
        window.setAttributes(p);

        this.setCanceledOnTouchOutside(false);

    }

    @Override
    public void show() {
        PreferencesHelper.saveData(AppConst.KEY_IS_GO_TO_BACKGROUND, false);
        PreferencesHelper.saveData(AppConst.KEY_DIALOG_SHOW_TIME, Calendar.getInstance().getTimeInMillis());
        super.show();

    }

    @Override
    public void dismiss() {
        PreferencesHelper.saveData(AppConst.KEY_IS_GO_TO_BACKGROUND, false);
        super.dismiss();
    }

    protected AgentWebX5.CommonAgentBuilder getWebBuilder() {
        long p = System.currentTimeMillis();
        return AgentWebX5.with(mContext)
                //new LinearLayout.LayoutParams(-1, -1)
                .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1))
                //.useDefaultIndicator()
                //.defaultProgressBarColor()
                // .setIndicatorColor(UIUtils.getColor(R.color.apptheme))
                .closeProgressBar()
                .setReceivedTitleCallback(mCallback).
                        setWebChromeClient(mWebChromeClient).
                        setWebViewClient(mWebViewClient).
                        setSecutityType(AgentWebX5.SecurityType.strict);
    }

    public WebView getWebView() {
        WebView mWebView = null;
        if (mAgentWeb != null) {
            mWebView = mAgentWeb.getWebCreator().get();
        }
        return mWebView;

    }

    public void initAgentWeb(String url) {
        mAgentWeb = getWebBuilder().createAgentWeb().ready().go(url);
        getWebView().setBackgroundColor(UIUtils.getColor(android.R.color.transparent));
        getWebView().setBackgroundResource(R.color.apptheme_bg);
        if (App.testWhendebug()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // getWebView().setWebContentsDebuggingEnabled(true);
            }
        }
        //设置 缓存模式
        getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        getWebView().getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        getWebView().getSettings().setDatabaseEnabled(true);
        // getWebView().getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        // getWebView().getSettings().setDomStorageEnabled(true);

        WebSettings webSetting = getWebView().getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mContext.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mContext.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        CookieSyncManager.createInstance(mContext);
        CookieSyncManager.getInstance().sync();

    }

}
